package com.noble.meether.fragment.rob.util;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.library.log.PSP;

/**
 * 抢聊大厅：工具类
 */
public class RobUtil implements Handler.Callback {
    private volatile static RobUtil mInstance;

    private RobUtil() {
        initHandler();
    }

    public static RobUtil getInstance() {
        if (mInstance == null) {
            synchronized (RobUtil.class) {
                if (mInstance == null) {
                    mInstance = new RobUtil();
                }
            }
        }
        return mInstance;
    }

    private void initHandler() {
        Looper looper;
        if ((looper = Looper.myLooper()) != null) {
            poolHandler = new Handler(looper, this);
        } else if ((looper = Looper.getMainLooper()) != null) {
            poolHandler = new Handler(looper, this);
        } else {
            poolHandler = null;
        }
    }

    // ==========================================  抢聊消息通知  =====================================
    private static final String ROB_NOTICE = "rob_notice";    // 抢聊消息通知

    /**
     * @param status 开关状态
     */
    public void setRobNotice(boolean status) {
        PSP.getInstance().put(ROB_NOTICE, status);
    }

    public boolean getRobNotice() {
        return PSP.getInstance().getBoolean(ROB_NOTICE, false);
    }

    // ==========================================  抢聊轮询  =====================================
    private static final int LOCATION_EVENT_START = 0x10;       // Handler msg
    public static final long INTERVAL_POOL_TIME = 5000;       // pool轮询间隔(单位：ms)
    private Handler poolHandler = null; // 聊天池轮询
    private PoolCallback callback;      // 聊天池刷新回调

    public interface PoolCallback {
        void onRefresh(HttpResponse response);
    }

    public void setPoolCallback(PoolCallback callback) {
        this.callback = callback;
    }

    /**
     * 开启付费轮询
     */
    public void startPoolTime() {
        reqChatPool();      // 马上请求
        stopPoolTime();
        if (poolHandler == null) {
            initHandler();
        }
        poolHandler.sendEmptyMessageDelayed(LOCATION_EVENT_START, INTERVAL_POOL_TIME);
    }

    /**
     * 关闭付费轮询
     */
    public void stopPoolTime() {
        if (poolHandler != null) {
            poolHandler.removeMessages(LOCATION_EVENT_START);
        }
    }

    /**
     * 轮询付费信息
     */
    private void reqChatPool() {
        ModuleMgr.getRtcChatMgr().reqChatPool(response -> {
            if (callback != null) {
                callback.onRefresh(response);
            }
        });
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case LOCATION_EVENT_START:
                startPoolTime();
                break;
        }
        return false;
    }
}
